/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.msk.wlhy.service;


import com.msk.common.utils.StringUtils;
import com.msk.sys.domain.Office;
import com.msk.sys.domain.User;
import com.msk.sys.service.BaseService;
import com.msk.sys.service.CrudService;
import com.msk.sys.utils.OfficeUtils;
import com.msk.wlhy.domain.HtCarFiles;
import com.msk.wlhy.domain.HtDriverFile;
import com.msk.wlhy.mapper.HtCarFilesDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 车辆档案维护Service
 *
 * @author zkp
 * @version 2018-06-06
 */
@Service
@Transactional(readOnly = true)
public class HtCarFilesService extends CrudService<HtCarFilesDao, HtCarFiles> {

	@Autowired
	private HtDriverFileService htDriverFileService;

	public HtCarFiles get(String id) {
		return super.get(id);
	}

	public List<HtCarFiles> findList(HtCarFiles htCarFiles) {
		// htCarFiles.getSqlMap().put("dsf",
		// BaseService.dataScopeFilter(htCarFiles.getCurrentUser(), "o4", "u"));
		return super.findList(htCarFiles);
	}

//	public Page<HtCarFiles> findPage(Page<HtCarFiles> page, HtCarFiles htCarFiles) {
//		return super.findPage(page, htCarFiles);
//	}

	@Transactional(readOnly = false)
	public void save(HtCarFiles htCarFiles) {
		htCarFiles.setState("1");
		//设置默认值下
		if(StringUtils.isBlank(htCarFiles.getVehicleOwnership())){
			htCarFiles.setVehicleOwnership("2");
		}
		if (StringUtils.isEmpty(htCarFiles.getId())) {
			htCarFiles.setStatus("1");// 新增车辆默认为可用
		}
		if(StringUtils.isBlank(htCarFiles.getCarType())){
			htCarFiles.setCarType("H01");
		}

		if(StringUtils.isBlank(htCarFiles.getLicenseType())){
			htCarFiles.setLicenseType("01");
		}

		if(StringUtils.isBlank(htCarFiles.getCarWeightType())){
			htCarFiles.setCarWeightType("0");
		}
		if (StringUtils.isEmpty(htCarFiles.getId())) { // 添加司机信息
			if (htCarFiles.getMasterDriverUser() != null) {
				HtDriverFile htDriverFile = htDriverFileService
						.getHtDriverFileByPhone(htCarFiles.getMasterDriverUser().getPhone());
				if (htDriverFile == null) {
					htDriverFile = htCarFiles.getMasterDriverUser();
					Office office = OfficeUtils.getOffice(htCarFiles.getOffice().getId());
					htDriverFile.setOffice(office);
					htDriverFile.setCompany(office.getParent());
					htDriverFile.setAttstr01("1");
					htDriverFile.setAttstr02(htCarFiles.getCarNumber());
					htDriverFileService.save(htDriverFile);
				} else {
					htDriverFile.setAttstr01("1");
					htDriverFile.setAttstr02(htCarFiles.getCarNumber());
					//htDriverFile.preUpdate();
					htDriverFileService.save(htDriverFile);
					htCarFiles.setMasterDriverUser(htDriverFile);
				}
			}
		}else{
			//修改驾驶员的图片
			if(htCarFiles.getMasterDriverUser() != null ){
				HtDriverFile htDriverFile = htDriverFileService.get(htCarFiles.getMasterDriverUser().getId());
				htDriverFile.setLicensePic(htCarFiles.getMasterDriverUser().getLicensePic());
				htDriverFile.setAttstr01("1");
				htDriverFile.setAttstr02(htCarFiles.getCarNumber());
				//htDriverFile.preUpdate();
				htDriverFileService.save(htDriverFile);
			}
		}
//		if(StringUtils.isNotEmpty(htCarFiles.getLng())&&StringUtils.isNotEmpty(htCarFiles.getLat())){
//			JSONObject jsonObject1 = SendMsgUtils.getIpLocal(htCarFiles.getUpdateIp());
//			if (jsonObject1 != null && jsonObject1.getString("status").equals("0")) { // 获取当前ip的地址位置
//				JSONObject jsonBody = jsonObject1.getJSONObject("content").getJSONObject("point");
//				if (jsonBody != null) {
//					Double lngD = (Double.parseDouble(jsonBody.getString("x")) + Math.random() / 100);
//					Double latD = (Double.parseDouble(jsonBody.getString("y")) + Math.random() / 100);
//					htCarFiles.setLng(lngD.toString());
//					htCarFiles.setLat(latD.toString());
//				}
//			}
//		}
		String[] officeIds = htCarFiles.getOffice().getId().split(",");
		if (StringUtils.isNotBlank(htCarFiles.getId())) {
			HtCarFiles oldhtCarFiles = this.get(htCarFiles.getId());
			oldhtCarFiles = this.findEntityByCarNumber(oldhtCarFiles.getCarNumber());
			String[] oldOfficeIds = null;
			if (oldhtCarFiles != null && oldhtCarFiles.getOffice() != null) {
				oldOfficeIds = oldhtCarFiles.getOffice().getId().split(",");
			}
            if(oldOfficeIds!=null){
                for (String string : oldOfficeIds) {
                    if (!htCarFiles.getOffice().getId().contains(string)) {
                        Office office = OfficeUtils.getOffice(string);
                        HtCarFiles carFiles = new HtCarFiles();
                        carFiles.setCarNumber(htCarFiles.getCarNumber());
                        carFiles.setOffice(office);
                        List<HtCarFiles> list = this.findList(carFiles);
                        if (list.size() > 0) {
                            this.delete(list.get(0));
                        }
                    }
                }
                if (officeIds.length >= 1) {
                    for (String officeId : officeIds) {
                        Office office = OfficeUtils.getOffice(officeId);
                        htCarFiles.setOffice(office);
                        htCarFiles.setCompany(office.getParent());
                        HtCarFiles carFiles = new HtCarFiles();
                        carFiles.setCarNumber(htCarFiles.getCarNumber());
                        carFiles.setOffice(office);
                        List<HtCarFiles> list = this.findList(carFiles);
                        if (list.size() > 0) {
                            htCarFiles.setId(list.get(0).getId());
                            htCarFiles.setVersion(list.get(0).getVersion());
                            super.save(htCarFiles);
                        } else {
                        	if(StringUtils.isBlank(htCarFiles.getId())){
								htCarFiles.setId(null);
								htCarFiles.setVersion(0);
								super.save(htCarFiles);
							}
                        }
                    }
                }
            }
		} else {
			for (String officeId : officeIds) {
				Office office = OfficeUtils.getOffice(officeId);
				htCarFiles.setOffice(office);
				htCarFiles.setCompany(office.getParent());
				super.save(htCarFiles);
			}
		}
	}
	@Transactional(readOnly = false)
	public void saveOnly(HtCarFiles htCarFiles) {
		super.save(htCarFiles);
	}
	@Transactional(readOnly = false)
	public void saveMobile(HtCarFiles htCarFiles) {
		super.save(htCarFiles);

		//new SaveHtCarFileThread(htCarFiles).start();
	}
	@Transactional(readOnly = false)
	public void delete(HtCarFiles htCarFiles) {
		super.delete(htCarFiles);
	}

	@Transactional(readOnly = false)
	public int deleteIds(String[] ids) {
		int result = 0;
		for (String id : ids) {
			HtCarFiles htCarFiles = get(id);
			HtCarFiles queryCarFiles = new HtCarFiles();
			queryCarFiles.setCarNumber(htCarFiles.getCarNumber());

			List<HtCarFiles> list = findListAll(queryCarFiles);
			for (HtCarFiles htCarFiles2 : list) {
				super.delete(htCarFiles2);
			}
			result++;
		}
		return result;
	}

	/**
	 * 根据运输单明细表id获取车辆对象集合 @param htCarFiles @return List<HtCarFiles> @throws
	 */
	public List<HtCarFiles> findListByTransportDetailId(HtCarFiles htCarFiles) {
		return dao.findListByTransportDetailId(htCarFiles);
	}

	/**
	 * @description findEntityByCarNumber
	 * @date 2018-6-19
	 * @author chuming
	 * @param carNumber
	 * @return
	 */
	public HtCarFiles findEntityByCarNumber(String carNumber) {
		return dao.findEntityByCarNumber(carNumber);
	}

	/**
	 * 根据司机手机号获取当前司司机可以查看那些部门的货物数据
	 *
	 * @description getOfficeIdsByPhone
	 * @date 2018-7-23
	 * @author chuming
	 * @return
	 */
	public String getOfficeIdsByPhone(String phone) {
		Map<String, String> map = dao.getOfficeIdsByPhone(phone);
		String officeIds = null;
		if (map!=null && !map.isEmpty()) {
			officeIds = map.get("officeIds");
		}
		return officeIds;
	}

	/**
	 * 根据司机手机号获取当前部门的车辆信息
	 *
	 * @description getOfficeIdsByPhone
	 * @date 2018-7-23
	 * @author chuming
	 * @param
	 * @return
	 */
	public HtCarFiles getCarFilesByPhone(HtCarFiles htCarFiles) {
		return dao.getCarFilesByPhone(htCarFiles);
	}

	/**
	 * 获取车辆信息
	 *
	 * @description selectCarCountGroupbyMonth
	 * @date 2018-8-9
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> selectCarCountGroupbyMonth(Integer xs1) {
		return dao.selectCarCountGroupbyMonth(xs1);
	}

	/**
	 * 获取车辆信息
	 *
	 * @description selectCarCountGroupbyDay
	 * @date 2018-8-9
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> selectCarCountGroupbyDay(Integer xs1) {
		return dao.selectCarCountGroupbyDay(xs1);
	}

	/**
	 * 获取各个部门车辆数量
	 *
	 * @description selectDeptOrderBy
	 * @date 2018-8-9
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> selectDeptOrderBy() {
		return dao.selectDeptOrderBy();
	}

	/**
	 * 查询未分组数据
	 *
	 * @description findListAll
	 * @date 2018-6-20
	 * @author chuming
	 * @return
	 */
	public List<HtCarFiles> findListAll(HtCarFiles htCarFiles) {
		return dao.findListAll(htCarFiles);
	}

	/**
	 * 获取各个部门车辆数量
	 *
	 * @description findCarNumberByOfficeAndDay
	 * @date 2018-10-25
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> findCarNumberByOfficeAndDay(HtCarFiles htCarFiles) {
		return dao.findCarNumberByOfficeAndDay(htCarFiles);
	}

	/**
	 * 获取所有的车辆数量
	 *
	 * @description findCarNumberByDay
	 * @date 2018-10-25
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> findAllCarNumberByDay(HtCarFiles htCarFiles) {
		return dao.findAllCarNumberByDay(htCarFiles);
	}

	/**
	 *
	 * @Title: saveWeixin
	 * @Description: 微信保存司机方法
	 * @param: @param htCarFiles
	 * @param: @param officeIdsb
	 * @param: @param driverFile1
	 * @param: @param office
	 * @return: void
	 * @author: chuming
	 * @date 2018年12月20日下午5:51:37
	 */
	@Transactional(readOnly = false)
	public void saveWeixin(HtCarFiles htCarFiles, String[] ids, HtDriverFile driverFile1, Office office) {
		// htCarFiles.setOffice(driverFile1.getOffice());
		// htCarFiles.setCompany(driverFile1.getCompany());
		driverFile1.setAttstr01("1");
		driverFile1.setAttstr02(htCarFiles.getCarNumber());
		driverFile1.setOffice(office);
		driverFile1.setCompany(office.getParent()==null || "0".equals(office.getParent().getId()) ? office : office.getParent());
		htDriverFileService.save(driverFile1);

		HtCarFiles oldhtCarFiles = this.findEntityByCarNumber(htCarFiles.getCarNumber());
		//String[] officeIds = ids.split(",");

		if(!StringUtils.isEmpty(htCarFiles.getId())){
			String[] oldOfficeIds = null;
			if (oldhtCarFiles != null && oldhtCarFiles.getOffice() != null) {
				oldOfficeIds = oldhtCarFiles.getOffice().getId().split(",");
			}

			for (String string : oldOfficeIds) {
				if (!Arrays.asList(ids).contains(string)) {
					Office office1 = OfficeUtils.getOffice(string);
					HtCarFiles carFiles = new HtCarFiles();
					carFiles.setCarNumber(htCarFiles.getCarNumber());
					carFiles.setOffice(office1);
					List<HtCarFiles> list = this.findList(carFiles);
					if (list.size() > 0) {
						this.delete(list.get(0));
					}
				}

			}
		}


		if (ids.length >= 1) {
			for (String officeId : ids) {
				Office office1 = OfficeUtils.getOffice(officeId);
				htCarFiles.setOffice(office1);
				htCarFiles.setCompany(office1.getParent()==null?office1:office1.getParent());
				HtCarFiles carFiles = new HtCarFiles();
				carFiles.setCarNumber(htCarFiles.getCarNumber());
				carFiles.setOffice(office1);
				List<HtCarFiles> list = this.findList(carFiles);
				if (list.size() > 0) {
					htCarFiles.setId(list.get(0).getId());
					htCarFiles.setVersion(list.get(0).getVersion());
					super.save(htCarFiles);
				} else {
					htCarFiles.setId(null);
					htCarFiles.setVersion(0);
					super.save(htCarFiles);
				}
			}
		}
		//new SaveHtCarFileThread(htCarFiles).start();

	}
	/**
	 * @description getHtDriverFile
	 * @date 2019-01-16
	 * @author chuming
	 * @param id
	 * @return
	 */
	public List<HtCarFiles> getHtCarFiles(String id){
		return dao.getHtCarFiles(id);
	}

	public Long findCount(HtCarFiles htCarFiles){
		return dao.findCount(htCarFiles);
	}

	/**
	 * @description findDriverCarId
	 * @date 2019-01-16
	 * @author chuming
	 * @param id
	 * @return
	 */
	public Map<String,Object> findDriverCarId(String id){
		return dao.findDriverCarId(id);
	}

	/**
	 * @description getRegister
	 * @date 2019-01-16
	 * @author chuming
	 * @param id
	 * @return
	 */
	public Map<String,Object> getRegister(String id){
		return dao.getRegister(id);
	}

	/**
	 * @description findAppId
	 * @date 2019-01-16
	 * @author chuming
	 * @param id
	 * @return
	 */
	public Map<String,Object> findAppId(String id){
		return dao.findAppId(id);
	}

	/**
	 * 更新车辆数据
	 * @param htCarFiles
	 * @return
	 */
	@Transactional(readOnly = false)
	public int updateInfo(HtCarFiles htCarFiles) {
		return dao.updateInfo(htCarFiles);
	}

	public List<Map<String,Object>> findPageByTransportStauts(HtCarFiles htCarFiles) {
		return dao.findListByTransportStauts(htCarFiles);
	}

	public boolean checkDriverFileInfo(HtCarFiles htCarFiles){
	    List<HtCarFiles> htCarFilesList = dao.findAllList(htCarFiles);
		if(htCarFilesList!=null && htCarFilesList.size()>0){
			for (HtCarFiles htcarFiles:htCarFilesList) {
				//如果找到符合条件的司机已经存在则不能再添加司机
				if(htcarFiles!=null && htcarFiles.getMasterDriverUser()!=null && StringUtils.isNotBlank(htcarFiles.getMasterDriverUser().getId())){
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 根据注册司机ID获取车辆信息
	 * @param driverId
	 * @return
	 */
	public HtCarFiles findCarFilesByDriverId(String driverId) {
		return dao.findCarFilesByDriverId(driverId);
	}

	@Transactional(readOnly = false)
	public void saveBackend(HtCarFiles htCarFiles) {
		htCarFiles.setState("1");
		//设置默认值下
		if(StringUtils.isBlank(htCarFiles.getVehicleOwnership())){
			htCarFiles.setVehicleOwnership("2");
		}
		if (StringUtils.isEmpty(htCarFiles.getId())) {
			htCarFiles.setStatus("1");// 新增车辆默认为可用
		}
		if(StringUtils.isBlank(htCarFiles.getCarType())){
			htCarFiles.setCarType("H01");
		}

		if(StringUtils.isBlank(htCarFiles.getLicenseType())){
			htCarFiles.setLicenseType("01");
		}

		if(StringUtils.isBlank(htCarFiles.getCarWeightType())){
			htCarFiles.setCarWeightType("0");
		}

		String[] officeIds = htCarFiles.getOffice().getId().split(",");

		User u = null;
		if(StringUtils.isBlank(htCarFiles.getIsPassCheck())){
			if(u != null && (StringUtils.isNotBlank(u.getUserIdentity())||StringUtils.isNotBlank(u.getMainAccountId()))){
				htCarFiles.setIsPassCheck("0");
			}else{
				htCarFiles.setIsPassCheck("1");
			}
		}
		if (StringUtils.isNotBlank(htCarFiles.getId())) {
			HtCarFiles oldhtCarFiles = this.get(htCarFiles.getId());
			oldhtCarFiles = this.findEntityByCarNumber(oldhtCarFiles.getCarNumber());
			String[] oldOfficeIds = null;
			if (oldhtCarFiles != null && oldhtCarFiles.getOffice() != null) {
				oldOfficeIds = oldhtCarFiles.getOffice().getId().split(",");
			}
			if(oldOfficeIds!=null){
				for (String string : oldOfficeIds) {
					if (!htCarFiles.getOffice().getId().contains(string)) {
						Office office = OfficeUtils.getOffice(string);
						HtCarFiles carFiles = new HtCarFiles();
						carFiles.setCarNumber(htCarFiles.getCarNumber());
						carFiles.setOffice(office);
						List<HtCarFiles> list = this.findList(carFiles);
						if (list.size() > 0) {
							this.delete(list.get(0));
						}
					}
				}
				if (officeIds.length >= 1) {
					for (String officeId : officeIds) {
						Office office = OfficeUtils.getOffice(officeId);
						htCarFiles.setOffice(office);
						htCarFiles.setCompany(office.getParent());
						HtCarFiles carFiles = new HtCarFiles();
						carFiles.setCarNumber(htCarFiles.getCarNumber());
						carFiles.setOffice(office);
						List<HtCarFiles> list = this.findList(carFiles);
						if (list.size() > 0) {
							htCarFiles.setId(list.get(0).getId());
							htCarFiles.setVersion(list.get(0).getVersion());
							super.save(htCarFiles);
						} else {
							if(StringUtils.isBlank(htCarFiles.getId())){
								htCarFiles.setId(null);
								htCarFiles.setVersion(0);
								super.save(htCarFiles);
							}
						}
					}
				}
			}
		} else {
			for (String officeId : officeIds) {
				Office office = OfficeUtils.getOffice(officeId);
				htCarFiles.setOffice(office);
				htCarFiles.setCompany(office.getParent());
				super.save(htCarFiles);
			}
		}
	}
}